package com.lanou.horo.zhuizhui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.lanou.horo.zhuizhui.R;
import com.lanou.horo.zhuizhui.entity.greendao.UserMsgDaoHelper;
import com.lanou.horo.zhuizhui.entity.greendao.User_Message;
import com.lanou.horo.zhuizhui.utility.clickInterface.UtilQQ;
import com.lanou.horo.zhuizhui.utility.imageLoader.BaseApplication;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by dllo on 15/10/23.
 */
public class LogInActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView logInBackBtn;
    private TextView WeiXinBtn, QQBtn, WeiBoBtn;
    private Button loginBtn, loginTv;
    private EditText userNameEt, userPasswordEt;
    private UserMsgDaoHelper helper;



    private static final String TAG = LogInActivity.class.getName();
    public static String mAppid;
    public static QQAuth mQQAuth;
    private UserInfo mInfo;
    private Tencent mTencent;
    private final String APP_ID = "222222";
    private TextView mUserInfo;
    private ImageView mUserLogo;
    private LinearLayout QQloginLinearLayout,qqmessageLinearLayout;
    private Bitmap userBitmap;
    private String mName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "-->onCreate");
        setContentView(R.layout.activity_login);
        initView();
    }

    private void initView() {

        qqmessageLinearLayout = (LinearLayout) findViewById(R.id.qqmessageLinearLayout);
        QQloginLinearLayout = (LinearLayout) findViewById(R.id.QQloginLinearLayout);
        mUserInfo = (TextView) findViewById(R.id.user_nickname);
        mUserLogo = (ImageView) findViewById(R.id.user_logo);
        logInBackBtn = (ImageView) findViewById(R.id.logInBackBtn);
        logInBackBtn.setOnClickListener(this);
        WeiXinBtn = (TextView) findViewById(R.id.WeiXinBtn);
        WeiBoBtn = (TextView) findViewById(R.id.WeiBoBtn);
        QQBtn = (TextView) findViewById(R.id.QQBtn);
        WeiXinBtn.setOnClickListener(this);
        WeiBoBtn.setOnClickListener(this);
        QQBtn.setOnClickListener(this);
        loginTv = (Button) findViewById(R.id.loginTv);
        loginTv.setOnClickListener(this);
        loginBtn = (Button) findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(this);
        userNameEt = (EditText) findViewById(R.id.userNameEt);
        userPasswordEt = (EditText) findViewById(R.id.userPasswordEt);
        helper = UserMsgDaoHelper.getInstance();
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_container);
        View.OnClickListener listener = new NewClickListener();
        for (int i = 0; i < linearLayout.getChildCount(); i++) {
            View view = linearLayout.getChildAt(i);
            if (view instanceof Button) {
                view.setOnClickListener(listener);
            }
        }
        updateLoginButton();


    }




    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.logInBackBtn:
                finish();
                break;
            case R.id.WeiXinBtn:
                showCustomToast("还是先安装微信吧~~ ", R.mipmap.ic_launcher);
                break;
            case R.id.WeiBoBtn:
                showCustomToast("暂停使用,换个方式登录吧", R.mipmap.ic_launcher);
                break;
            case R.id.QQBtn:
//                showProgressDialog();
                if (!mQQAuth.isSessionValid()) {
                    IUiListener listener = new BaseUiListener() {
                        @Override
                        protected void doComplete(JSONObject values) {
                            updateUserInfo();
                            updateLoginButton();
                        }
                    };
                    mQQAuth.login(this, "all", listener);
                    // mTencent.loginWithOEM(this, "all",
                    // listener,"10000144","10000144","xxxx");
                    mTencent.login(this, "all", listener);
                } else {
                    mQQAuth.logout(this);
                    updateUserInfo();
                    updateLoginButton();
                }
                break;
            case R.id.loginTv:
                Intent intent = new Intent(this, RegisteredActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.loginBtn:
                String name = userNameEt.getText().toString();
                String password = userPasswordEt.getText().toString();
                // 判断输入内容是否为空
                if (!name.equals("") && !password.equals("")) {
                    User_Message usermsg = helper.getUsermsgByName(name);
                    if (usermsg != null) {
                        if (name.equals(usermsg.getName())) {
                            if (password.equals(usermsg.getPassWord())) {
                                showCustomToast("登录成功", R.mipmap.ic_launcher);
                                BaseApplication.setIslogin(true);
                                Intent intentlog = new Intent(this,
                                        UserInformationActivity.class);
                                BaseApplication.setUser(helper.getUsermsgByName(name));
                                startActivity(intentlog);
                                finish();
                            } else {
                                showCustomToast("密码不正确", R.mipmap.ic_launcher);}
                        } else {
                            showCustomToast("用户名不正确", R.mipmap.ic_launcher);}
                    } else {
                        showCustomToast("用户不存在", R.mipmap.ic_launcher);}
                } else {
                    showCustomToast("用户名和密码不能为空", R.mipmap.ic_launcher);}
                break;
        }
    }
    private void showCustomToast(String s, int image) {
        //获取LayoutInflater对象，该对象可以将布局文件转换成与之一致的view对象
        LayoutInflater inflater = getLayoutInflater();
        //将布局文件转换成相应的View对象
        View layout = inflater.inflate(R.layout.custome_toast_layout,
                (ViewGroup) findViewById(R.id.toast_layout_root));
        //从layout中按照id查找imageView对象
        ImageView imageView = (ImageView) layout.findViewById(R.id.ivForToast);
        //设置ImageView的图片
        imageView.setBackgroundResource(image);
        //从layout中按照id查找TextView对象
        TextView textView = (TextView) layout.findViewById(R.id.tvForToast);
        //设置TextView的text内容
        textView.setText(s);
        //实例化一个Toast对象
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 600);
        toast.setView(layout);
        toast.show();
    }
    /**
     * 弹出一个ProgressDialog进度框
     **/

//      public void showProgressDialog() {
//        final ProgressDialog pd = new ProgressDialog(this);
//        pd.setMessage("QQ授权登录中");
//
//        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//
//        pd.setMax(100);
//
//        pd.show();
//        final Intent QQintent = new Intent();
//        Thread t = new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(3000);
//                    pd.dismiss();//关闭ProgressDialog
//                    QQintent.setClass(getApplicationContext(), QQloginlogin.class);
//                    startActivity(QQintent);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//        t.start();
//    }



    @Override
    protected void onStart() {
        Log.d(TAG, "-->onStart");
        final Context context = this;
        final Context ctxContext = context.getApplicationContext();
        mAppid = APP_ID;
        mQQAuth = QQAuth.createInstance(mAppid, ctxContext);
        mTencent = Tencent.createInstance(mAppid, this);
        super.onStart();
    }


    @Override
    protected void onResume() {
        Log.d(TAG, "-->onResume");
        super.onResume();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "-->onPause");
        super.onPause();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "-->onStop");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "-->onDestroy");
        super.onDestroy();
    }

    private void updateUserInfo() {

        if (mQQAuth != null && mQQAuth.isSessionValid()) {
            IUiListener listener = new IUiListener() {
                @Override
                public void onError(UiError e) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onComplete(final Object response) {
                    Message msg = new Message();
                    msg.obj = response;
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                    new Thread() {

                        @Override
                        public void run() {
                            JSONObject json = (JSONObject) response;
                            if (json.has("figureurl")) {
                                Bitmap bitmap = null;
                                try {
                                    bitmap = UtilQQ.getbitmap(json
                                            .getString("figureurl_qq_2"));
                                } catch (JSONException e) {

                                }
                                Message msg = new Message();
                                msg.obj = bitmap;
                                msg.what = 1;
                                mHandler.sendMessage(msg);
                            }
                        }

                    }.start();

                }

                @Override
                public void onCancel() {

                }
            };
            mInfo = new UserInfo(this, mQQAuth.getQQToken());
            mInfo.getUserInfo(listener);

        } else {
//            mUserInfo.setText("");
//            mUserInfo.setVisibility(View.GONE);
//            mUserLogo.setVisibility(View.GONE);

        }
    }

    Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                JSONObject response = (JSONObject) msg.obj;
                if (response.has("nickname")) {
                    try {
                        mUserInfo.setVisibility(View.VISIBLE);
                        mUserInfo.setText(response.getString("nickname"));
                        mName = response.getString("nickname");
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            } else if (msg.what == 1) {
                Bitmap bitmap = (Bitmap) msg.obj;
                mUserLogo.setImageBitmap(bitmap);
                mUserLogo.setVisibility(View.VISIBLE);
                userBitmap = bitmap;
            }
        }

    };



    public static boolean ready(Context context) {
        if (mQQAuth == null) {
            return false;
        }
        boolean ready = mQQAuth.isSessionValid()
                && mQQAuth.getQQToken().getOpenId() != null;
        if (!ready)
            Toast.makeText(context, "",
                    Toast.LENGTH_SHORT).show();
        return ready;
    }

    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            UtilQQ.showResultDialog(LogInActivity.this, /*response.toString()*/"成功获得授权",
                    "登录成功");

            doComplete((JSONObject) response);
        }

        protected void doComplete(JSONObject values) {

        }

        @Override
        public void onError(UiError e) {
//            UtilQQ.toastMessage(LogInActivity.this, "onError: " + e.errorDetail);
            UtilQQ.dismissDialog();
        }

        @Override
        public void onCancel() {
//            UtilQQ.toastMessage(LogInActivity.this, "onCancel: ");
            UtilQQ.dismissDialog();
        }
    }


    class NewClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Context context = v.getContext();
            Class<?> cls = null;
            switch (v.getId()) {
                case R.id.QQBtn:

                    return;
            }
            if (cls != null) {
                Intent intent = new Intent(context, cls);
//                BaseApplication.setIslogin(true);
//                BaseApplication.setUser(helper.getUsermsgByName(mName));
                context.startActivity(intent);
            }
        }
    }
    private void updateLoginButton() {
        if (mQQAuth != null && mQQAuth.isSessionValid()) {
            QQBtn.setTextColor(Color.RED);
            QQBtn.setText(R.string.qq_logout);
            qqmessageLinearLayout.setVisibility(View.VISIBLE);
            QQloginLinearLayout.setVisibility(View.INVISIBLE);
            mUserLogo.setVisibility(View.VISIBLE);
            mUserInfo.setVisibility(View.VISIBLE);
        } else {
            QQBtn.setTextColor(Color.BLUE);
            QQBtn.setText(R.string.qq_login);
            qqmessageLinearLayout.setVisibility(View.INVISIBLE);
            QQloginLinearLayout.setVisibility(View.VISIBLE);

        }
    }
}
